<template>
  <div class="user-list">
    <div class="list-header">
      <h3>联系人</h3>
      <button class="btn-icon" @click="showAddFriend = true">
        <Icon icon="mdi:add" />
      </button>
    </div>
    
    <div class="search-box">
      <input 
        v-model="searchQuery" 
        type="text" 
        placeholder="搜索联系人..." 
        class="search-input"
        @input="handleSearch"
      />
    </div>
    
    <div class="users-container">
      <div v-if="filteredUsers.length === 0" class="empty-state">
        {{ searchQuery ? '未找到相关联系人' : '暂无联系人' }}
      </div>
      
      <div 
        v-for="user in filteredUsers" 
        :key="user.id" 
        class="user-item"
        :class="{ active: isActiveUser(user.id) }"
        @click="selectUser(user)"
      >
        <img :src="user.avatar" class="user-avatar" />
        <div class="user-info">
          <div class="user-name">{{ user.username }}</div>
          <div class="user-status">
            <span :class="['status-dot', user.status]"></span>
            {{ user.status === 'online' ? '在线' : `最后在线: ${formatTime(user.lastSeen)}` }}
          </div>
        </div>
        <div v-if="user.unreadCount > 0" class="unread-count">
          {{ user.unreadCount }}
        </div>
      </div>
    </div>
    
    <!-- 添加好友模态框 -->
    <div v-if="showAddFriend" class="modal-overlay" @click.self="showAddFriend = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3>添加好友</h3>
          <button class="btn-close" @click="showAddFriend = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>用户名或邮箱</label>
            <input 
              v-model="searchFriendQuery" 
              type="text" 
              class="form-input" 
              placeholder="输入用户名或邮箱"
              @input="handleFriendSearch"
            />
          </div>
          
          <div v-if="searchResults.length > 0" class="search-results">
            <div 
              v-for="user in searchResults" 
              :key="user.id" 
              class="search-result-item"
            >
              <img :src="user.avatar" class="result-avatar" />
              <div class="result-info">
                <div class="result-name">{{ user.username }}</div>
                <div class="result-email">{{ user.email }}</div>
              </div>
              <button 
                v-if="!user.isFriend" 
                class="btn btn-primary btn-sm"
                @click="addFriend(user.id)"
              >
                添加
              </button>
              <span v-else class="friend-label">已是好友</span>
            </div>
          </div>
          
          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showAddFriend = false">取消</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { Icon } from '@iconify/vue';
import { useChatStore } from '@/stores/chat'
import { debounce } from 'lodash'

export default {
  name: 'UserList',
  props: {
    activeUserId: {
      type: Number,
      default: null
    }
  },
  setup(props, { emit }) {
    const chatStore = useChatStore()
    
    const searchQuery = ref('')
    const searchFriendQuery = ref('')
    const showAddFriend = ref(false)
    
    const users = computed(() => chatStore.friends)
    const searchResults = computed(() => chatStore.users)
    
    const filteredUsers = computed(() => {
      if (!searchQuery.value) return users.value
      
      return users.value.filter(user => 
        user.username.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        (user.email && user.email.toLowerCase().includes(searchQuery.value.toLowerCase()))
      )
    })
    
    onMounted(async () => {
      await chatStore.loadFriends()
    })
    
    const isActiveUser = (userId) => {
      return props.activeUserId === userId
    }
    
    const selectUser = (user) => {
      emit('user-selected', user)
    }
    
    const handleSearch = () => {
      // 搜索逻辑已通过 computed 属性处理
    }
    
    const handleFriendSearch = debounce(() => {
      if (searchFriendQuery.value.trim()) {
        chatStore.searchUsers(searchFriendQuery.value.trim())
      }
    }, 500)
    
    const addFriend = async (userId) => {
      const result = await chatStore.addFriend(userId)
      if (result.success) {
        searchFriendQuery.value = ''
        showAddFriend.value = false
        await chatStore.loadFriends()
      } else {
        alert(result.message || '添加好友失败')
      }
    }
    
    const formatTime = (time) => {
      if (!time) return ''
      
      const date = new Date(time)
      const now = new Date()
      const diff = now - date
      const minutes = Math.floor(diff / (1000 * 60))
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (minutes < 1) {
        return '刚刚'
      } else if (minutes < 60) {
        return `${minutes}分钟前`
      } else if (hours < 24) {
        return `${hours}小时前`
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return date.toLocaleDateString()
      }
    }
    
    // 当模态框关闭时清空搜索结果
    watch(showAddFriend, (newVal) => {
      if (!newVal) {
        searchFriendQuery.value = ''
        chatStore.users = []
      }
    })
    
    return {
      searchQuery,
      searchFriendQuery,
      showAddFriend,
      users,
      searchResults,
      filteredUsers,
      isActiveUser,
      selectUser,
      handleSearch,
      handleFriendSearch,
      addFriend,
      formatTime
    }
  }
}
</script>

<style scoped>
.user-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
}

.list-header h3 {
  margin: 0;
}

.btn-icon {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 4px;
}

.btn-icon:hover {
  background-color: #f0f0f0;
}

.search-box {
  padding: 0.5rem 1rem;
}

.search-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.users-container {
  flex: 1;
  overflow-y: auto;
}

.empty-state {
  text-align: center;
  padding: 2rem;
  color: #999;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 0.75rem 1rem;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
}

.user-item:hover {
  background-color: #f9f9f9;
}

.user-item.active {
  background-color: #e8f4f8;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  margin-right: 0.75rem;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.user-status {
  font-size: 0.875rem;
  color: #666;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 0.25rem;
}

.status-dot.online {
  background-color: #07c160;
}

.status-dot.offline {
  background-color: #999;
}

.unread-count {
  background-color: #fa5151;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.75rem;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h3 {
  margin: 0;
}

.btn-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
}

.modal-body {
  padding: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-results {
  margin-top: 1rem;
}

.search-result-item {
  display: flex;
  align-items: center;
  padding: 0.75rem;
  border-bottom: 1px solid #f0f0f0;
}

.result-avatar {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 0.75rem;
}

.result-info {
  flex: 1;
}

.result-name {
  font-weight: 500;
}

.result-email {
  font-size: 0.875rem;
  color: #666;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.friend-label {
  color: #07c160;
  font-size: 0.875rem;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 1rem;
}

.btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #f0f0f0;
  color: #333;
}

.btn-secondary:hover {
  background-color: #e0e0e0;
}

.btn-primary {
  background-color: #07c160;
  color: white;
}

.btn-primary:hover {
  background-color: #06ae56;
}
</style>